package com.et.mvc.easy;



/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2009</p>
 * <p>Company: Sangame.com</p>
 * @author liuyi
 * <p>CreateDate: Dec 2, 2009 2:34:27 PM</p>
 * @version 1.0
 */
import java.io.File;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;


public class PojoFactory {
	//定义生成文件的包路径
	private static String pack = "com.jimmy.models";
	
	//定义要反射出的数据库
	private static String driver = "com.mysql.jdbc.Driver";
	private static String url = "jdbc:mysql://localhost:3306/sailing";
	private static String username = "root";//mksp
	private static String password = "root";//sangame.com
//	private static String driver = "oracle.jdbc.driver.OracleDriver";
//	private static String url = "jdbc:oracle:thin:@192.168.1.110:1521:sgdb";//mksp@
//	private static String username = "mksp";//mksp
//	private static String password = "sangame.com";//sangame.com
	
	
	public static void main(String[] args) {
		
		new PojoFactory().writeEtmvcPojo();//创建Etmvc的pojo文件,需要数据库驱动包以及et-ar.jar
		//new PojoFactory().writePojo();//创建原始的pojo文件,需数据库驱动包
	}

	public void writeEtmvcPojo() {
		Connection conn = null;
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, username, password);

			DatabaseMetaData dbmd = conn.getMetaData();
			
			
			if("com.mysql.jdbc.Driver".equals(driver)){
				String[] types = { "TABLE" };
				ResultSet resultSet = dbmd.getTables(null, "mksp", "%", types);
				while (resultSet.next()) {
					String tableName = resultSet.getString("TABLE_NAME");
					System.out.println(tableName);
					String className = String.valueOf(tableName.charAt(0))
							.toUpperCase()
							+ tableName.substring(1);

					File path = new File(System.getProperty("user.dir")+"\\src\\"+pack.replace('.', '\\')); 
					//String path = filePath.toString()+"\\src\\"+pack.replace('.', '\\')+"\\";
					System.out.println("path================="+path);
					if (!path.exists()) {
						path.mkdirs();
					}
					FileOutputStream fos = new FileOutputStream(path+"\\" + className
							+ ".java", false);
					StringBuilder sb = new StringBuilder();
					StringBuilder one = new StringBuilder();
					StringBuilder two = new StringBuilder();
					StringBuilder three = new StringBuilder();
					one.append("package "+pack+";\r\n");
					one.append("/**" +"\r\n"
	                        + " * <p>Title: </p>"+"\r\n"
	                        + " * <p>Company: Sangame.com</p> "+"\r\n"
	                        + " * @author liuyi"+"\r\n"
	                        + " * @version 1.0"+"\r\n"
	                        + " */"+"\r\n");
					one.append("import com.et.ar.ActiveRecordBase;" + "\r\n"
							+ "import com.et.ar.annotations.Column;" + "\r\n"
							+ "import com.et.ar.annotations.Id;" + "\r\n"
							+ "import com.et.ar.annotations.Table;" + "\r\n");
					two.append("\r\n\r\n@Table(name=\"" + tableName + "\")\r\n");
					two.append("public class " + className
							+ " extends ActiveRecordBase {" + "\r\n");

					String timestamp = "";
					String date = "";
					String time = "";
					
					String sql = "select * from " +tableName;
					System.out.println(sql);
					
					ResultSetMetaData rsmd = null;

					Statement stmt = conn.createStatement();
					ResultSet rs = stmt.executeQuery(sql);
					rsmd = rs.getMetaData();
					
					for (int i = 1; i <= rsmd.getColumnCount(); i++) {
						String s = rsmd.getColumnTypeName(i);
						String type = s;
						if (s.indexOf(" ") != -1) {// 防止取出的类似type====INTEGER
													// UNSIGNED
							type = s.substring(0, s.indexOf(" "));
						}

						String name = rsmd.getColumnName(i).toLowerCase();
						System.out.println("type====" + type);
						System.out.println("name====" + name);
						ResultSet pkRSet = dbmd.getPrimaryKeys(null, null,
								tableName);
						String keyName = "";
						// 取出表中的主键名字
						while (pkRSet.next()) {
							keyName = pkRSet.getObject("COLUMN_NAME").toString();
						}

						System.out.println("keyName=====" + keyName);
						String sid = "Column";
						if (keyName.equals(name)) {
							sid = "Id";
						}
						if (type.trim().equalsIgnoreCase("Integer")){
							type = "Integer";
						} else if (type.trim().equalsIgnoreCase("Varchar")) {
							type = "String";
						} else if (type.trim().equalsIgnoreCase("BIGINT")) {
							type = "Long";
						} else if (type.trim().equalsIgnoreCase("DOUBLE")) {
							type = "Double";
						} else if (type.trim().equalsIgnoreCase("FLOAT")) {
							type = "Float";
						} else if (type.trim().equalsIgnoreCase("Timestamp")) {
							type = "Timestamp";
							timestamp = "yes";
						} else if (type.trim().equalsIgnoreCase("Date")) {
							type = "Date";
							date = "yes";
						} else if (type.trim().equalsIgnoreCase("Datetime")) {
							type = "Timestamp";
							timestamp = "yes";
						} else if (type.trim().equalsIgnoreCase("TIME")) {
							type = "Time";
							time = "yes";
						} else if (type.trim().equalsIgnoreCase("YEAR")) {
							type = "Date";
							date = "yes";
						} else {
							type = "String";
						}

						String outs = "    @" + sid + " private " + type + " "
								+ name + ";\r\n";
						two.append(outs);

						// get set
						// 首字母转大写
						String name2 = String.valueOf(name.charAt(0)).toUpperCase()
								+ name.substring(1).toLowerCase();
						String set = "    public void set" + name2 + "(" + type
								+ " " + name + "){\r\n" + "        this." + name
								+ " = " + name + ";\r\n" + "    }\r\n";
						String get = "    public " + type + " get" + name2
								+ "(){\r\n" + "        return " + name + ";\r\n"
								+ "    }\r\n";
						three.append(get);
						three.append(set);
					}
					if (timestamp.equals("yes")) {
						one.append("import java.sql.Timestamp;" + "\r\n");
					}
					if (time.equals("yes")) {
						one.append("import java.sql.Time;" + "\r\n");
					}
					if (date.equals("yes")) {
						one.append("import java.sql.Date;" + "\r\n");
					}
					sb.append(one);
					sb.append(two);
					sb.append(three);
					sb.append("}");

					String temp = sb.toString();
					fos.write(temp.getBytes());
					fos.close();

				}
			}else if("oracle.jdbc.driver.OracleDriver".equals(driver)){
				Statement st = conn.createStatement();
				ResultSet resultSet = st.executeQuery("SELECT   *   FROM   USER_ALL_TABLES");
				while (resultSet.next()) {
					String tableName = resultSet.getString("TABLE_NAME");
					System.out.println(tableName);
					String className = String.valueOf(tableName.charAt(0))
							.toUpperCase()
							+ tableName.substring(1);
					String sql = "select * from " +tableName;
					System.out.println(sql);
					ResultSetMetaData rsmd = null;

					Statement stmt = conn.createStatement();
					ResultSet rs = stmt.executeQuery(sql);
					rsmd = rs.getMetaData();

					File path = new File(System.getProperty("user.dir")+"\\src\\"+pack.replace('.', '\\')); 
					//String path = filePath.toString()+"\\src\\"+pack.replace('.', '\\')+"\\";
					System.out.println("path================="+path);
					if (!path.exists()) {
						path.mkdirs();
					}
					FileOutputStream fos = new FileOutputStream(path+"\\" + className
							+ ".java", false);
					StringBuilder sb = new StringBuilder();
					StringBuilder one = new StringBuilder();
					StringBuilder two = new StringBuilder();
					StringBuilder three = new StringBuilder();
					one.append("package "+pack+";\r\n");
					one.append("/**" +"\r\n"
	                        + " * <p>Title: </p>"+"\r\n"
	                        + " * <p>Company: Sangame.com</p> "+"\r\n"
	                        + " * @author liuyi"+"\r\n"
	                        + " * @version 1.0"+"\r\n"
	                        + " */"+"\r\n");
					one.append("import com.et.ar.ActiveRecordBase;" + "\r\n"
							+ "import com.et.ar.annotations.Column;" + "\r\n"
							//+ "import com.et.ar.annotations.Id;" + "\r\n"
							+ "import com.et.ar.annotations.Table;" + "\r\n");
					two.append("\r\n\r\n@Table(name=\"" + tableName + "\")\r\n");
					two.append("public class " + className
							+ " extends ActiveRecordBase {" + "\r\n");

					String timestamp = "";
					String date = "";
					String id = "";
					for (int i = 1; i <= rsmd.getColumnCount(); i++) {
						String s = rsmd.getColumnTypeName(i);
						String type = s;
//						if (s.indexOf(" ") != -1) {// 防止取出的类似type====INTEGER
//													// UNSIGNED
//							type = s.substring(0, s.indexOf(" "));
//						}

						String name = rsmd.getColumnName(i).toLowerCase();
						System.out.println("type====" + type);
						System.out.println("name====" + name);
						ResultSet pkRSet = dbmd.getPrimaryKeys(null, null,
								tableName);
						String keyName = "";
						// 取出表中的主键名字
						while (pkRSet.next()) {
							keyName = pkRSet.getObject("COLUMN_NAME").toString();
						}

						System.out.println("keyName=====" + keyName);
						String sid = "Column";
						if (keyName.equals(name)) {
							sid = "Id";
							id = "yes";//有主键时设置id="yes"使程序自动导入import com.et.ar.annotations.Id;
						}
						if (type.trim().equalsIgnoreCase("Number")){
							type = "Integer";
						} else if (type.trim().equalsIgnoreCase("Varchar2")) {
							type = "String";
						} else if (type.trim().equalsIgnoreCase("SMALLINT")) {
							type = "Short";
						} else if (type.trim().equalsIgnoreCase("DOUBLE")) {
							type = "Double";
						} else if (type.trim().equalsIgnoreCase("REAL")) {
							type = "Float";
						} else if (type.trim().equalsIgnoreCase("Timestamp")) {
							type = "Timestamp";
							timestamp = "yes";
						} else if (type.trim().equalsIgnoreCase("Date")) {
							type = "Date";
							date = "yes";
						}  else {
							type = "String";
						}

						String outs = "    @" + sid + " private " + type + " "
								+ name + ";\r\n";
						two.append(outs);

						// get set
						// 首字母转大写
						String name2 = String.valueOf(name.charAt(0)).toUpperCase()
								+ name.substring(1).toLowerCase();
						String set = "    public void set" + name2 + "(" + type
								+ " " + name + "){\r\n" + "        this." + name
								+ " = " + name + ";\r\n" + "    }\r\n";
						String get = "    public " + type + " get" + name2
								+ "(){\r\n" + "        return " + name + ";\r\n"
								+ "    }\r\n";
						three.append(get);
						three.append(set);
					}
					if (id.equals("yes")) {
						one.append("import com.et.ar.annotations.Id;" + "\r\n");
					}
					if (timestamp.equals("yes")) {
						one.append("import java.sql.Timestamp;" + "\r\n");
					}
					
					if (date.equals("yes")) {
						one.append("import java.sql.Date;" + "\r\n");
					}
					sb.append(one);
					sb.append(two);
					sb.append(three);
					sb.append("}");

					String temp = sb.toString();
					fos.write(temp.getBytes());
					fos.close();

				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (conn != null) {
					conn.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}
	
}
